class Solution
{
public:
    int getMaxLen(vector<int> &nums)
    {
        int maxLen = 0;
        int n = nums.size();

        // 以0分割子数组，含begin，不含end，统计负数个数，以及第一个/最后一个负数位置
        int begin = 0;
        int end = 0;
        int negCount = 0;
        int firstNeg = -1;
        int lastNeg = -1;

        auto updateMaxLen = [&]()
        {
            if (negCount & 1)
            {
                maxLen = max(maxLen, max(end - firstNeg - 1, lastNeg - begin));
            }
            else
            {
                maxLen = max(maxLen, end - begin);
            }
        };

        while (end < n)
        {
            if (nums[end] < 0)
            {
                ++negCount;
                if (firstNeg == -1)
                {
                    firstNeg = end;
                }
                lastNeg = end;
            }
            else if (nums[end] == 0)
            {
                updateMaxLen();
                begin = end + 1;
                negCount = 0;
                firstNeg = -1;
                lastNeg = -1;
            }
            ++end;
        }

        updateMaxLen();

        return maxLen;
    }
};